package com.osremake.server.net.codec;

import org.jboss.netty.buffer.ChannelBuffer;
import org.jboss.netty.buffer.ChannelBuffers;
import org.jboss.netty.channel.Channel;
import org.jboss.netty.channel.ChannelHandlerContext;
import org.jboss.netty.handler.codec.replay.ReplayingDecoder;
import org.jboss.netty.handler.codec.replay.VoidEnum;

import java.security.SecureRandom;

/**
 * @author kyle
 */
public class LoginDecoder extends ReplayingDecoder<VoidEnum> {
    @Override
    protected Object decode(ChannelHandlerContext channelHandlerContext, Channel channel, ChannelBuffer channelBuffer, VoidEnum voidEnum) throws Exception {
        int opcode = channelBuffer.readUnsignedByte();
        switch(opcode) {
            case 14:
                int nameHash = channelBuffer.readUnsignedByte();
                ChannelBuffer handshake = ChannelBuffers.dynamicBuffer(17);
                for(int i = 0; i < 9; i++) {
                    handshake.writeByte(0);
                }
                handshake.writeLong(new SecureRandom().nextLong());
                channel.write(handshake);
                break;
            case 16:
            case 18:
                int loginCode = channelBuffer.readUnsignedByte();
                int packetSize = channelBuffer.readUnsignedByte();
                int magicCode = channelBuffer.readUnsignedByte();
                int version = channelBuffer.readUnsignedShort();
                int detail = channelBuffer.readUnsignedByte();
                for(int i = 0; i < 9; i++) { //CRC checksum.
                    channelBuffer.readInt();
                }
                int rsa = channelBuffer.readUnsignedByte();
                long clientKey = channelBuffer.readLong();
                long serverKey = channelBuffer.readLong();
                int uid = channelBuffer.readInt();
                ChannelBuffer login = ChannelBuffers.dynamicBuffer(3);
                login.writeByte(2);
                login.writeByte(0);
                login.writeByte(0);
                channel.write(login);
                break;
        }
        return null;
    }
}
